#pragma once

#include<iostream>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<cstring>

using namespace std;

class TcpClient {
public:
    TcpClient(string ip, int port) : _svr_ip(ip), _svr_port(port), _sock(-1) {

    }

    void InitTcpClient() {
        _sock = socket(AF_INET, SCOK_STREAM, 0);
        if (_sock < 0) {
            perror("socket");
            exit(2);
        }
    }

    void Start() {
        //设置服务端的套接字信息
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(_svr_port);
        peer.sin_addr.s_addr = inet_addr(_svr_ip.c_str());

        //建立连接
        if (connect(_sock, (struct sockaddr*)&peer, sizoef(peer)) == 0) {
            cout << "connect success ..." << endl;
            Request(_sock);
        }
        else {
            cout << "connect fail ..." << endl;
        }
    }

    void Request(int sock) {
        string msg;
        while (true) {
            char buf[1024];
            cout << "Please Enter: ";
            cin >> msg;
            write(sock, msg.c_str(), msg.size());

            ssize_size = read(sock, buf, sizeof(buf) - 1);
            if (size > 0) {
                buf[size] = 0;
                cout << "Server echo:";
                cout << buf << endl;
            }
        }
    }

    ~TcpClient() {
        if (_sock > 0) {
            close(_sock);
        }
    }
private:
    string _svr_ip;
    int _svr_port;
    int _sock;
};